<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传和下载</title>
    <script src="${ pageContext.request.contextPath }/js/jquery-3.6.0.js" type="text/javascript"></script>
</head>
<body>
<table border="1">
    <tr>
        <td width="200" align="center">文件上传${msg}${path}</td>
        <td width="300" align="center">下载列表</td>
    </tr>
    <tr>
        <td height="100">
            <form id="uploadForm"  enctype="multipart/form-data">
                用户名：<input type="text" name="username" /><br/>

                <input type="file" name="files" multiple="multiple"><br/>
            </form>
            <input type="reset" value="清空"/>
            <input type="button" value="提交" onclick="sumbmit()"/>
            <img id="img" width="200px" height="200px">
        </td>
        <td id="files"><a href="${pageContext.request.contextPath}/download?filename=test.pdf">下载</a>该图片</h1>
        </td>
    </tr>
</table>

<script type="text/javascript">
    function sumbmit() {
        console.log($('#uploadForm'))

        var formData = new FormData($('#uploadForm')[0]);
        console.log(formData)
        $.ajax({
            url: "${pageContext.request.contextPath }/fileloadbyajax",
            type: "post",
            data: formData,
            processData: false, //默认为true，规定通过请求发送的数据是否转换为查询字符串,这里告诉他不处理发送的数据
            contentType: false, //不设置contentType 如果是true 会是application/x-www-form-urlencoded，我们要用multipart/form-data
            success: function (response) {
                console.log(response)
                if(response.code !=0 ) {
                    console.log(response.msg);
                } else {
                   $("#img")[0].src = ${pageContext.request.contextPath}/files/ + response.data;

                   $("a").attr("href","${pageContext.request.contextPath}/download?filename="+ response.data)
                    //window.location.href="${pageContext.request.contextPath }/ajax/toshow"

                }
            },
            error: function (response) {
                console.log(response)
                alert(response);
            }
        });
    }


</script>
</body>

</html>

